package juc.producerandconsumer;

import javafx.scene.paint.Stop;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用synchronize wait notify/notifyall
 * 实现单生产者单消费者模式
 * 还不对，以后再改
 */

public class reentrantLock {
    public static AtomicInteger atomicInteger = new AtomicInteger();
    public volatile boolean flag = true;
    public static final int MAX_COUNT = 10;
    public static final List<Integer> pool = new ArrayList<>();
    ReentrantLock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public void produce() {
        lock.lock();
        try {
            while (flag) {
                //池子满了，生产者停止生产
                while (pool.size() == MAX_COUNT) {
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                pool.add(atomicInteger.incrementAndGet());
                System.out.println(Thread.currentThread().getName() + "正在生产" + atomicInteger.get() + "号商品" + "\t" + "当前商品数：" + pool.size());
                condition.signalAll();
            }
        } finally {
            lock.unlock();
        }

    }


    public void consumue() {
        lock.lock();
        try {
            // 判断，干活，通知
            while (flag) {

                //没有商品，停止消费
                while (pool.size() == 0) {
                    try {
                        System.out.println("pool is empty, wating...");
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                int temp = pool.get(0);
                pool.remove(0);
                System.out.println(Thread.currentThread().getName() + "正在消费" + temp + "号商品" + "\t" + "当前商品数：" + pool.size());
                condition.signalAll();
            }
        } finally {
            lock.unlock();
        }
    }

    public void stop() {
        flag = false;
    }
}

class ProducerConsumer {

    public static void main(String[] args) {
        reentrantLock shareDataV1 = new reentrantLock();
        new Thread(() -> {
            shareDataV1.produce();
        }, "AAA").start();

        new Thread(() -> {
            shareDataV1.consumue();
        }, "BBB").start();

        new Thread(() -> {
            shareDataV1.produce();

        }, "CCC").start();

        new Thread(() -> {
            shareDataV1.consumue();
        }, "DDD").start();

        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        shareDataV1.stop();

    }
}